<template>
  <div>
    <el-dialog
      :modal="false"
      title="用户详细信息"
      :visible.sync="userDetailVisible"
      style=""
      class="userDetailDialog"
    >
      <div
        style="
          display: flex;
          justify-content: space-between;
          flex-direction: row;
          flex-wrap: wrap;
        "
      >
        <div style="width: 680px; display: flex; justify-content: space-around">
          <div class="top_show">
            压力类型
            <el-select
              style="margin-left: 7px"
              size="small"
              v-model="userDetailForm.pressureType"
              multiple
              placeholder="全部"
            >
            </el-select>
          </div>
          <div class="top_show">
            户名<el-input
              style="margin-left: 7px; width: 150px"
              size="small"
              v-model="userDetailForm.pressureType"
              placeholder="请输入内容"
            ></el-input>
          </div>
          <div class="top_show">
            地址<el-input
              style="margin-left: 7px; width: 150px"
              size="small"
              v-model="userDetailForm.address"
              placeholder="请输入内容"
            ></el-input>
          </div>
        </div>

        <div style="width: 300px; display: flex; justify-content: flex-end">
          <div>
            添加户号<el-input
              style="margin-left: 7px; margin-right: 7px; width: 150px"
              size="small"
              v-model="userDetailForm.userCode"
              placeholder="请输入内容"
            ></el-input>
          </div>
          <div>
            <el-button size="small" type="primary" plain>添加</el-button>
          </div>
        </div>
      </div>
      <div style="height: 200px; overflow: auto">
        <el-table
          border
          :data="userGroupList"
          style="width: 100%; margin-top: 10px"
        >
          <el-table-column type="selection" width="85"> </el-table-column>
          <el-table-column label="序号" width="160"> </el-table-column>
          <el-table-column prop="name" label="户号" width="160">
          </el-table-column>
          <el-table-column prop="name" label="户名" width="160">
          </el-table-column>
          <el-table-column prop="address" label="地址"> </el-table-column>
          <el-table-column prop="name" label="口径" width="160">
          </el-table-column>
          <el-table-column prop="name" label="压力级别" width="160">
          </el-table-column>
        </el-table>
      </div>
      <div>
        <div style="margin-top: 10px">
          停水编号：<el-input
            style="margin-left: 40px; width: 85%"
            size="small"
          ></el-input>
        </div>
        <div style="margin-top: 10px">
          停水标题：<el-input
            style="margin-left: 40px; width: 85%"
            size="small"
          ></el-input>
        </div>
        <div style="margin-top: 10px">
          <span style="line-height: 50px">停水原因：</span
          ><el-input
            style="margin-left: 40px; width: 85%"
            size="small"
            type="textarea"
          ></el-input>
        </div>
        <div style="margin-top: 10px">
          实施地点：<el-input
            style="margin-left: 40px; width: 85%"
            size="small"
          ></el-input>
        </div>
        <div
          style="
            margin-top: 10px;
            width: 85%;
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <div style="width: 500px">
            <span style="margin-right: 40px">停水类型：</span>
            <el-radio label="1">计划性停水</el-radio>
            <el-radio label="2">临时停水</el-radio>
          </div>
          <div>
            口径：<el-input style="width: 150px" size="small"></el-input>
          </div>
        </div>
        <div style="margin-top: 10px">
          <span style="line-height: 50px">停水时间：</span>
          <el-date-picker
            style="margin-left: 40px"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>
        <div style="margin-top: 10px">
          <span style="line-height: 50px">实际操作时间：</span>
          <el-date-picker
            style="margin-left: 11px"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>
        <div style="margin-top: 10px">
          <span style="line-height: 50px">停水区域：</span
          ><el-input
            style="margin-left: 40px; width: 85%"
            size="small"
            type="textarea"
          ></el-input>
        </div>
        <div style="margin-top: 10px">
          <span style="line-height: 50px">停水备注：</span
          ><el-input
            style="margin-left: 40px; width: 85%"
            size="small"
            type="textarea"
          ></el-input>
        </div>
      </div>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <el-button type="primary" size="small" plain>推送OA</el-button>
        <el-button style="margin-left: 15px" type="primary" size="small" plain
          >直接推送微信</el-button
        >
        <el-button
          style="margin-left: 15px"
          type="primary"
          size="small"
          plain
          @click="userDetailVisible = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
    <div
      style="
        padding-left: 5px;
        width: 100%;
        height: 30px;
        font-size: 15px;
        color: #fff;
        line-height: 30px;
        background-color: #4070a2;
      "
    >
      点击地图获取施工位置
    </div>
    <div style="display: flex; justify-content: center">
      <el-button
        icon="el-icon-s-flag"
        style="width: 220px; margin-top: 7px; margin-bottom: 7px"
        type="info"
        plain
        @click="getPoint"
        >请选择施工点</el-button
      >
    </div>
    <div>
      <el-table
        :data="pointGroupList"
        border
        style="width: 100%; max-height: 15rem; overflow-y: scroll"
        @row-click="handlePointListClick"
        height="200"
      >
        <el-table-column prop="date" label="序号" width="" align="center">
          <template slot-scope="scope">
            {{ scope.row.index }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="描述" align="center">
          <template slot-scope="scope">
            {{ scope.row.coordinate }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="" label="" width="" align="center">
          <template slot-scope="scope">
            <el-button @click.stop="delPointFromTable(scope.row.index)"
              >删除</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>
    </div>
    <div
      style="
        margin-top: 5px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
      "
    >
      <!-- <el-checkbox v-model="checked" style="color: #3ea41c"
        >是否考虑水源</el-checkbox
      > -->
      <div>
        <el-button
          type="primary"
          icon="el-icon-check"
          plain
          style="margin-right: 7px"
          @click="executeAnalysis"
          v-if="!isSecondAnalysis"
          >执行</el-button
        >
        <el-button
          type="primary"
          style="margin-right: 7px"
          v-else
          @click="secondAnalysis"
          >二次关阀</el-button
        >
        <el-button type="primary" plain @click="getPoint">重新选择</el-button>
      </div>
    </div>
    <div
      style="
        padding-left: 5px;
        width: 100%;
        height: 30px;
        font-size: 15px;
        color: #fff;
        line-height: 30px;
        background-color: #4070a2;
        margin-top: 5px;
      "
    >
      分析结果
    </div>
    <div style="margin-top: 5px">
      <div
        style="
          display: flex;
          justify-content: space-around;
          width: 120px;
          font-size: 15px;
        "
      >
        <div>所在道路：</div>
        <div>{{ calResultData.lineNum }}条</div>
      </div>
      <div
        style="
          display: flex;
          justify-content: space-around;
          width: 120px;
          font-size: 15px;
        "
      >
        <div>影响阀门：</div>
        <div>{{ calResultData.lineimpactValveNum }}个</div>
      </div>
      <div
        style="
          display: flex;
          justify-content: space-around;
          width: 120px;
          font-size: 15px;
        "
      >
        <div>影响用户：</div>
        <div>{{ calResultData.impactUser }}户</div>
        <!-- <el-link type="primary" @click="showUserDetail">用户详情信息</el-link> -->
      </div>
      <div
        style="
          display: flex;
          justify-content: space-around;
          width: 158px;
          font-size: 15px;
        "
      >
        <div>影响范围：</div>
        <div>暂无范围</div>
      </div>
    </div>

    <div style="display: flex; justify-content: flex-end; margin-top: 5px">
      <el-button
        type="primary"
        plain
        style="margin-right: 7px"
        @click="showValveOperate"
        >阀门操作单</el-button
      >
      <el-button type="primary" icon="el-icon-finished" plain>保存</el-button>
      <el-button
        type="primary"
        icon="el-icon-printer"
        plain
        style="margin-right: 7px"
        >打印</el-button
      >
    </div>
  </div>
</template>
<script>
// import vavleManageForm from "./valveManageForm.vue";
import dmgis from "@/api/dmgis";
import { filterKeywordsByValve } from "@/api/EquipmentManagement";
import { point } from "@turf/turf";
import { transform, useGeographic, Projection, addProjection } from "ol/proj";
export default {
  // components: { vavleManageForm },
  data() {
    return {
      impactValveList: [],
      isSecondAnalysis: false,
      resultDataTemp: [],
      calResultData: {
        lineNum: 0,
        lineimpactValveNum: 0,
        impactUser: 0,
        impactArea: "",
      },
      executePoint: [],
      dmPipProjectLayer: null,
      // showValveOperate: false,
      cutoffWaterDetailForm: {
        code: "",
        title: "",
        reason: "",
        place: "",
        type: "",
        calibre: "",
        cutOffTime: "",
        operationTime: "",
        area: "",
        remark: "",
      },
      userGroupList: [],
      userDetailForm: {
        pressureType: "",
        userName: "",
        address: "",
        userCode: "",
      },

      tableData: [],
      userDetailVisible: false,
      tapMap: null,
      pointLayer: null,
      lineLayer: null,
      clickPointStore: null,
      pointGroupList: [],
      pointIndex: 1,
    };
  },
  mounted() {
    this.tapMap = this.$store.getters.Map;
    this.pointLayer = this.tapMap.layer.createVectorLayer("施工点图层", {}, 3);
    this.lineLayer = this.tapMap.layer.createVectorLayer("停水线段图层", {}, 2);
    //测试
    this.pointLayer.getSource().clear();
    this.lineLayer.getSource().clear();

    this.dmPipProjectLayer = this.$store.getters.pipProjectLayer;
  },
  methods: {
    secondAnalysis() {
      console.log(this.resultDataTemp, "this.resultDataTemp");
      let mapcontanier = document.querySelector(".ol-viewport");
      mapcontanier.style.cursor = "crosshair";
      if (this.dmPipProjectLayer) {
        this.tapMap.map.on("click", this.getPointByClick);
      } else {
        this.$message.error("请先加载管线数据！");
      }
    },
    arraysEqual(arr1, arr2) {
      if (arr1.length !== arr2.length) return false;
      for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) return false;
      }
      return true;
    },
    executeAnalysis() {
      if (this.resultDataTemp.length > 0) {
        let prjParmas = new dmgis.object.checkPointParmas(
          this.executePoint,
          "pipeLineNet",
          "Net"
        );
        this.dmPipProjectLayer.checkPoint(prjParmas).then(async (res) => {
          this.isSecondAnalysis = true;
          let coorData = res;
          if (!coorData.keywords) {
            this.$message.error("未查询到阀门信息！");
            let featuresCollection = this.pointLayer.getSource().getFeatures();
            let lastFeatureIndex = featuresCollection.length - 1;
            this.pointGroupList.pop();
            let lastFeature = featuresCollection[lastFeatureIndex];
            this.pointLayer.getSource().removeFeature(lastFeature);
            return;
          }
          //加点
          await filterKeywordsByValve(coorData.keywords).then((res) => {
            let point = res.data;
            this.impactValveList.push(...res.data);
            point.forEach((item) => {
              this.tapMap.marker.addMarker(
                item.xcoordinate,
                item.ycoordinate,
                this.pointLayer,
                {
                  text: {
                    font: "normal 10px 微软雅黑",
                    name: ++this.pointIndex + "",
                    fillColor: "#fff",
                    strokeColor: "#000",
                    strokeWidth: 2,
                    offsetY: 0,
                  },
                  scale: 1.5, //大小
                  radius: 10,
                  pBorderColor: "#000000",
                  pBorderWidth: 1,
                  pFillColor: "pink",
                },
                "",
                `${this.pointIndex}`
              );
            });
          });
          //加线
          if (coorData.posCoor.length == 1) {
            this.tapMap.marker.addLineString(
              this.executePoint,
              coorData.posCoor[0],
              this.lineLayer,
              {
                color: "#FF0000", // 红色
                width: 8,
              },
              "",
              ""
            );
          } else {
            //找最近的点
            let closestPointDistance = 0;
            let closestPoint = [];
            let lastTwoPoint = [
              coorData.posCoor[coorData.posCoor.length - 1],
              coorData.posCoor[coorData.posCoor.length - 2],
            ];
            lastTwoPoint.forEach((item, index) => {
              if (index == 0) {
                closestPointDistance = this.findPointDistance(
                  item,
                  this.executePoint
                );
                closestPoint = item;
              } else {
                let temp = this.findPointDistance(item, this.executePoint);
                if (temp < closestPointDistance) {
                  closestPointDistance = temp;
                  closestPoint = item;
                }
              }
            });
            this.tapMap.marker.addLineString(
              this.executePoint,
              closestPoint,
              this.lineLayer,
              {
                color: "#FF0000", // 红色
                width: 8,
              },
              "",
              ""
            );
            // let posTemp = coorData.posCoor[0];
            // console.log(coorData.posCoor, "posTempBefore");
            // coorData.posCoor.push(posTemp);
            // coorData.posCoor.push(this.executePoint);
            console.log(coorData.posCoor, "posTemp");
            this.executePoint;
            coorData.posCoor.forEach((item, index) => {
              let flag = index + 1;
              //加线
              if (flag % 2 == 0) {
                // this.calResultData.lineNum++;
                this.tapMap.marker.addLineString(
                  coorData.posCoor[flag - 2],
                  coorData.posCoor[flag - 1],
                  this.lineLayer,
                  {
                    color: "#FF0000", // 红色
                    width: 8,
                  },
                  "",
                  ""
                );
              }
            });
          }
        });
      } else {
        let prjParmas = new dmgis.object.checkPointParmas(
          this.pointGroupList[0].data,
          "pipeLineNet",
          "Net"
        );
        this.pointIndex = 0;
        this.calResultData = {
          lineNum: 0,
          lineimpactValveNum: 0,
          impactUser: 0,
          impactArea: "",
        };
        // this.pointLayer.getSource().clear();
        // this.lineLayer.getSource().clear();
        this.dmPipProjectLayer.checkPoint(prjParmas).then(async (res) => {
          this.isSecondAnalysis = true;
          let coorData = res;
          if (!coorData.keywords) {
            this.$message.error("未查询到阀门信息！");
            return;
          }
          //加点
          await filterKeywordsByValve(coorData.keywords).then((res) => {
            let point = res.data;
            this.impactValveList.push(...res.data);
            this.resultDataTemp.push(point);
            point.forEach((item) => {
              this.tapMap.marker.addMarker(
                item.xcoordinate,
                item.ycoordinate,
                this.pointLayer,
                {
                  text: {
                    font: "normal 10px 微软雅黑",
                    name: ++this.pointIndex + "",
                    fillColor: "#fff",
                    strokeColor: "#000",
                    strokeWidth: 2,
                    offsetY: 0,
                  },
                  scale: 1.5, //大小
                  radius: 10,
                  pBorderColor: "#000000",
                  pBorderWidth: 1,
                  pFillColor: "pink",
                },
                "",
                `${this.pointIndex}`
              );
            });
          });
          //加线
          if (coorData.posCoor.length == 1) {
            this.tapMap.marker.addLineString(
              this.executePoint,
              coorData.posCoor[0],
              this.lineLayer,
              {
                color: "#FF0000", // 红色
                width: 8,
              },
              "",
              ""
            );
          } else {
            //找最近的点
            let closestPointDistance = 0;
            let closestPoint = [];
            let lastTwoPoint = [
              coorData.posCoor[coorData.posCoor.length - 1],
              coorData.posCoor[coorData.posCoor.length - 2],
            ];
            lastTwoPoint.forEach((item, index) => {
              if (index == 0) {
                closestPointDistance = this.findPointDistance(
                  item,
                  this.executePoint
                );
                closestPoint = item;
              } else {
                let temp = this.findPointDistance(item, this.executePoint);
                if (temp < closestPointDistance) {
                  closestPointDistance = temp;
                  closestPoint = item;
                }
              }
            });
            this.tapMap.marker.addLineString(
              this.executePoint,
              closestPoint,
              this.lineLayer,
              {
                color: "#FF0000", // 红色
                width: 8,
              },
              "",
              ""
            );
            // let posTemp = coorData.posCoor[0];
            // console.log(coorData.posCoor, "posTempBefore");
            // coorData.posCoor.push(posTemp);
            // coorData.posCoor.push(this.executePoint);
            console.log(coorData.posCoor, "posTemp");
            this.executePoint;
            coorData.posCoor.forEach((item, index) => {
              let flag = index + 1;
              //加线
              if (flag % 2 == 0) {
                // this.calResultData.lineNum++;
                this.tapMap.marker.addLineString(
                  coorData.posCoor[flag - 2],
                  coorData.posCoor[flag - 1],
                  this.lineLayer,
                  {
                    color: "#FF0000", // 红色
                    width: 8,
                  },
                  "",
                  ""
                );
              }
            });
          }
        });
      }
    },
    findDuplicatesData(array) {
      var unique = new Map(); // 使用 Map 而不是 Set 来存储点的坐标和对应的点数组
      for (var i = 0; i < array.length; i++) {
        var key = `${array[i][0]},${array[i][1]}`;
        if (unique.has(key)) {
          // 如果坐标已存在，将当前点添加到对应的点数组中
          unique.get(key).push(array[i]);
        } else {
          // 如果坐标不存在，创建一个新数组并添加到 Map 中
          unique.set(key, [array[i]]);
        }
      }

      // 过滤出包含多个点的数组（即重复点组）
      var duplicatesGroups = Array.from(unique.values()).filter(
        (group) => group.length > 1
      );

      // 将所有重复点组展平为一个数组并返回
      return duplicatesGroups.flat();
    },
    findPointDistance(point1, point2) {
      let dx = point2[0] - point1[0];
      let dy = point2[1] - point1[1];
      return Math.sqrt(dx * dx + dy * dy);
    },
    showValveOperate() {
      this.$store.commit("setshowValveOperate", true);
    },
    delPointFromTable(index) {
      this.pointLayer
        .getSource()
        .getFeatures()
        .forEach((feature) => {
          if (feature.type == index) {
            this.pointLayer.getSource().removeFeature(feature);
          }
        });
      this.pointGroupList = this.pointGroupList.filter(
        (item) => item.index != index
      );
    },
    handlePointListClick(row) {
      this.tapMap.panTo([row.x, row.y], 22);
    },
    showUserDetail() {
      this.userDetailVisible = true;
    },
    getPoint() {
      this.isSecondAnalysis = false;
      this.pointLayer.getSource().clear();
      this.lineLayer.getSource().clear();
      this.pointIndex = 0;
      this.pointGroupList = [];
      this.executePoint = [];
      this.resultDataTemp = [];
      this.impactValveList = [];
      let mapcontanier = document.querySelector(".ol-viewport");
      mapcontanier.style.cursor = "crosshair";
      if (this.dmPipProjectLayer) {
        this.dmPipProjectLayer.InitService().then((res) => {
          this.pointLayer.getSource().clear();
          this.tapMap.map.on("click", this.getPointByClick);
        });
      } else {
        this.$message.error("请先加载管线数据！");
      }
    },
    getPointByClick(e) {
      this.isSecondAnalysis = false;
      this.tapMap.map.un("click", this.getPointByClick);
      this.executePoint = e.coordinate;
      let mapcontanier = document.querySelector(".ol-viewport");
      mapcontanier.style.cursor = "auto";
      if (this.resultDataTemp.length > 0) {
        this.tapMap.marker.addText(
          [this.executePoint[0], this.executePoint[1]],
          this.pointLayer,
          {
            name: `二次关闸点`,
            fillColor: "#FFF",
            font: "normal 10px 微软雅黑",
            strokeColor: "#000",
            strokeWidth: 2,
            offsetX: 0,
            offsetY: 0,
          }
        );
      } else {
        this.tapMap.marker.addMarker(
          this.executePoint[0],
          this.executePoint[1],
          this.pointLayer,
          {
            text: {
              font: "normal 13px 微软雅黑",
              name: this.resultDataTemp.length > 0 ? "二次关闸点" : `施工点`,
              fillColor: "#fff",
              strokeColor: "#000",
              strokeWidth: 2,
              offsetY: this.resultDataTemp.length > 0 ? 15 : 0,
            },
            scale: 1.5, //大小
            radius: 10,
            pBorderColor: "#000000",
            pBorderWidth: 2,
            pFillColor:
              this.resultDataTemp.length > 0
                ? "rgba(255, 255, 255, 0.5)"
                : "green",
          },
          "",
          `施工点`
        );
      }
      let x = this.executePoint[0];
      let y = this.executePoint[1];
      this.pointGroupList.push({
        index: this.pointIndex,
        coordinate:
          this.resultDataTemp.length > 0
            ? "二次关闸点" + `(${x},${y})`
            : "施工点：" + `(${x},${y})`,
        x: x,
        y: y,
        data: [x, y],
      });
    },
  },
  watch: {
    impactValveList(val) {
      console.log("impactValveList", val);
      if (val.length > 0) {
        this.calResultData.lineimpactValveNum = val.length;
        let roadNames = new Set();
        val.forEach((item) => roadNames.add(item.roadName));
        this.calResultData.lineNum = roadNames.size;
      } else {
        this.calResultData = {
          lineNum: 0,
          lineimpactValveNum: 0,
          impactUser: 0,
          impactArea: "",
        };
      }

      this.$store.commit("setImpactValveList", val);
    },
  },
  destroyed() {
    if (this.tapMap) {
      this.tapMap.map.un("click", this.getPointByClick);
      this.lineLayer.getSource().clear();
      this.pointLayer.getSource().clear();
      this.tapMap.map.removeLayer(this.pointLayer);
      this.tapMap.map.removeLayer(this.lineLayer);
    }
  },
};
</script>
<style lang="scss" scoped>
.top_show {
  display: flex;
  justify-content: space-between;
}
::v-deep.el-radio {
  color: white;
}
::v-deep .el-select {
  width: 8rem;
}
::-webkit-scrollbar {
  display: none;
}
.userDetailDialog {
  // background-color: #FFF;
  width: 45rem;
  height: 40rem;
  left: 27%;
  top: 9%;
  // top: 50%;
  // left: 50%;
  // transform: translate(-50%, -50%);
  // overflow: hidden;
  ::v-deep .el-dialog__wrapper {
    width: 33rem !important;
  }
  ::v-deep .el-dialog {
    // width: 70%;
    background-color: #285383;
    color: #fff;
    margin: 0;
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__body {
      color: #fff;
    }
  }
}
</style>
